package model

import (
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type Role struct {
	ID       uint   `gorm:"primaryKey;autoIncrement" json:"id"`
	Name     string `gorm:"size:64;not null;unique;column:name" json:"name"`
	CreateBy string `gorm:"size:64;not null;column:create_by" json:"create_by"`
}

func (r *Role) Create(tx *gorm.DB) error {
	if r.ID == 0 {
		result := tx.Create(r)
		if result.Error != nil {
			return errors.New("创建角色失败")
		}
	} else {
		result := tx.Save(r)
		if result.Error != nil {
			return errors.New("更新角色失败")
		}
	}
	return nil
}

func (r *Role) Delete(tx *gorm.DB) error {
	if err := tx.Model(r).Delete(r).Error; err != nil {
		return errors.New("删除角色失败")
	}
	return nil
}

func (r *Role) GetByName(tx *gorm.DB, name string) error {
	if err := tx.Model(r).Where("name = ?", name).First(r).Error; err != nil {
		return errors.New("获取角色失败")
	}
	return nil
}

func (r *Role) GetByID(tx *gorm.DB, id uint) error {
	if err := tx.Model(r).Where("id = ?", id).First(r).Error; err != nil {
		return errors.New("获取角色失败")
	}
	return nil
}

func (r *Role) List(tx *gorm.DB, page, pageSize int) ([]Role, error) {
	var roles []Role
	if err := tx.Model(r).Offset((page - 1) * pageSize).Limit(pageSize).Find(&roles).Error; err != nil {
		return nil, errors.New("获取角色列表失败")
	}
	return roles, nil
}
